import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 更新或创建单元格
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sheetId = params.id
    const body = await request.json()
    const { row, column, value, formula } = body

    if (typeof row !== 'number' || typeof column !== 'number') {
      return NextResponse.json({ error: 'Row and column must be numbers' }, { status: 400 })
    }

    // 使用 upsert 来更新或创建单元格
    const cell = await prisma.cell.upsert({
      where: {
        sheetId_row_column: {
          sheetId,
          row,
          column
        }
      },
      update: {
        value,
        formula
      },
      create: {
        sheetId,
        row,
        column,
        value,
        formula
      }
    })

    return NextResponse.json(cell)
  } catch (error) {
    console.error('Error updating cell:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// 获取表格的所有单元格 - 优化版本
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const sheetId = params.id
    const { searchParams } = new URL(request.url)
    
    // 支持分页参数
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '1000') // 默认1000条
    const skip = (page - 1) * limit
    
    // 支持范围查询参数
    const minRow = searchParams.get('minRow')
    const maxRow = searchParams.get('maxRow')
    const minCol = searchParams.get('minCol')
    const maxCol = searchParams.get('maxCol')
    
    // 构建查询条件
    const whereConditions: any = { sheetId }
    
    if (minRow || maxRow || minCol || maxCol) {
      whereConditions.AND = []
      
      if (minRow) whereConditions.AND.push({ row: { gte: parseInt(minRow) } })
      if (maxRow) whereConditions.AND.push({ row: { lte: parseInt(maxRow) } })
      if (minCol) whereConditions.AND.push({ column: { gte: parseInt(minCol) } })
      if (maxCol) whereConditions.AND.push({ column: { lte: parseInt(maxCol) } })
    }

    // 并行查询总数和分页数据
    const [cells, totalCount] = await Promise.all([
      prisma.cell.findMany({
        where: whereConditions,
        orderBy: [
          { row: 'asc' },
          { column: 'asc' }
        ],
        skip,
        take: limit
      }),
      prisma.cell.count({
        where: whereConditions
      })
    ])

    // 设置缓存头
    const response = NextResponse.json({ 
      cells,
      pagination: {
        page,
        limit,
        total: totalCount,
        totalPages: Math.ceil(totalCount / limit)
      }
    })
    
    // 设置缓存头，减少重复请求
    response.headers.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300')
    response.headers.set('ETag', `"${sheetId}-${totalCount}-${Date.now()}"`)
    
    return response
  } catch (error) {
    console.error('Error fetching cells:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
